package com.sales.util;


import com.sales.service.QuotationService;
import org.comple.erp.pojo.sales.Quotation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.List;


@Component
public class RedisKeyExpirationListener implements MessageListener {

    private final RedisTemplate<String, Object> redisTemplate;

    @Autowired
    QuotationService quotationService;


    public RedisKeyExpirationListener(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }
    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 正确获取过期的 key
        String expiredKey = new String(message.getBody(), StandardCharsets.UTF_8);

        System.out.println("Redis key expired: " + expiredKey);

        //其他带了前缀的 key直接退出处理
        if(expiredKey.startsWith("inquiry:") || expiredKey.startsWith("comparison:")){
            return;
        }

        handleExpiredKey(expiredKey);
    }

    /**
     * 处理过期键的业务逻辑
     * @param expiredKey 过期的键名
     */
    private void handleExpiredKey(String expiredKey) {//所有键过期都会来，检验是订单号

        if (expiredKey != null) {
            System.out.println("处理订单超时逻辑，订单号: {}  "+expiredKey);
            Quotation quotation = quotationService.selectByPrimaryKey(expiredKey);
            if(quotation != null){
                quotation.setValidStatus(1);
                quotationService.updateByPrimaryKeySelective(quotation);//订单状态改为超时

            }
        }

    }

}